package org.bigzero.postbank

import groovy.sql.Sql

class MetaDataDBService {
static transactional = true
	static final META_TABLE_NAME = "META_TABLE"
	def dataSource

	def resetTable(){
		def db = new Sql(dataSource)
		def rs = db.rows("select * from INFORMATION_SCHEMA.SYSTEM_COLUMNS where table_name = ${META_TABLE_NAME}")
		if (rs.size() == 0){
			createTable()
			return
		}
		
		def metaDataNameList = MetaData.list().name
		0.upto metaDataNameList.size() - 1, {metaDataNameList[it] = metaDataNameList[it].toUpperCase()}
		(rs.COLUMN_NAME - metaDataNameList).each {db.execute("alter table $META_TABLE_NAME drop column $it".toString())}
		(metaDataNameList - rs.COLUMN_NAME).each {db.execute("alter table $META_TABLE_NAME add column $it varchar".toString())}
	}
	
	def createTable(){
		def metaDataList = MetaData.list()
		if (!metaDataList || metaDataList.size() == 0) return
		def strSql = "create table ${META_TABLE_NAME} (${ MetaData.list().name.join(' varchar,')} varchar)"
		def db = new Sql(dataSource)
		db.execute(strSql.toString())
	}
}
